package masterjava.common.shared.util;

import masterjava.common.shared.Converter;
import masterjava.common.shared.Presentable;

import java.util.*;

/**
 * User: GKislin
 * Date: 22.01.11
 */
public class SharedUtil {

    public static Map<?, ?> asMap(Object... parameters) {
        Map<Object, Object> result = new HashMap<Object, Object>();
        for (int i = 0; i < parameters.length; i = i + 2) {
            result.put(parameters[i], parameters[i + 1]);
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    public static <E extends Enum> Map<E, ?> asEnumMap(Class<E> clazz, Object... parameters) {
        Map<E, Object> result = new EnumMap(clazz);
        for (int i = 0; i < parameters.length; i = i + 2) {
            result.put((E) parameters[i], parameters[i + 1]);
        }
        return result;
    }

    public static boolean isEmpty(Object[] array) {
        return (array == null || array.length == 0);
    }

    // Copy of Spring CollectionUtils at client side
    public static boolean isEmpty(Collection collection) {
        return (collection == null || collection.isEmpty());
    }

    // Copy of Spring StringUtils at client side
    public static <T> String collectionToDelimitedString(Iterable<T> coll, String delim) {
        return collectionToDelimitedString(coll, delim, "", "");
    }

    public static final Presentable PRESENTER = new Presentable() {
        @Override
        public CharSequence present(Object object) {
            return String.valueOf(object);
        }
    };

    public static <T> String collectionToDelimitedString(Iterable<T> coll, String delim, String prefix, String suffix) {
        return collectionToDelimitedString(coll, delim, prefix, suffix, PRESENTER);
    }

    public static <T> String collectionToDelimitedString(Iterable<T> coll, String delim, String prefix, String suffix, Presentable<T> presenter) {
        if (coll == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        Iterator<T> it = coll.iterator();
        while (it.hasNext()) {
            sb.append(prefix).append(presenter.present(it.next())).append(suffix);
            if (it.hasNext()) {
                sb.append(delim);
            }
        }
        return sb.toString();
    }

    public static <F, T> List<T> convertList(List<F> fromList, Converter<F, T> converter) {
        if (isEmpty(fromList)) {
            return Collections.EMPTY_LIST;
        }
        ArrayList<T> toList = new ArrayList<T>(fromList.size());
        for (F fromItem : fromList) {
            toList.add(converter.convert(fromItem));
        }
        return toList;
    }
}
